package com.tedu._03vehicle.base.response;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
public class RateLimitInterceptor implements HandlerInterceptor {
    private static final int MAX_REQUEST_COUNT=3;
    private static final int WINDOW_SIZE_SECOND = 60;
    private final ConcurrentHashMap<String,Integer> clientCounts =
            new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String , LocalDateTime> lastResetTime=
    new ConcurrentHashMap<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      log.debug("进入限流拦截器");
//        String remoteAddr = request.getRemoteAddr();
//        LocalDateTime localDateTime = lastResetTime.get(remoteAddr);
//        if (localDateTime == null| localDateTime.isAfter(
//                LocalDateTime.now().plusSeconds(WINDOW_SIZE_SECOND))) {
//            clientCounts.put(remoteAddr,0);
//            lastResetTime.put(remoteAddr,LocalDateTime.now());
//
//        }
//        Integer merge = clientCounts.merge(remoteAddr, 1, Integer::sum);
//        if (merge >3) {
//            throw new RuntimeException("访问过于频繁");
//        }
        String addr = request.getRemoteAddr();
        LocalDateTime localDateTime = lastResetTime.get(addr);
        if (localDateTime == null | localDateTime.isAfter(
                LocalDateTime.now().plusSeconds(WINDOW_SIZE_SECOND))) {
            clientCounts.put(addr,0);
            lastResetTime.put(addr,LocalDateTime.now());
        }
        Integer merge = clientCounts.merge(addr, 1, Integer::sum);
        if (merge >3) {
            throw new RuntimeException("访问过于频繁");
        }
        return true;
    }
}
